package com.compass.doctor.ui.message.fragment;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.compass.doctor.databinding.FragmentMyConversationBinding;
import com.netease.yunxin.kit.common.ui.viewmodel.FetchResult;
import com.netease.yunxin.kit.common.ui.viewmodel.LoadStatus;
import com.netease.yunxin.kit.common.utils.SizeUtils;
import com.netease.yunxin.kit.conversationkit.ui.ConversationKitClient;
import com.netease.yunxin.kit.conversationkit.ui.ConversationUIConfig;
import com.netease.yunxin.kit.conversationkit.ui.fun.FunViewHolderFactory;
import com.netease.yunxin.kit.conversationkit.ui.model.ConversationBean;
import com.netease.yunxin.kit.conversationkit.ui.page.ConversationBaseFragment;

import java.util.ArrayList;
import java.util.List;

/**
 * Description： 自己定义 的会话列表
 * Date:2023/11/24 10:53
 */
public class MyConversationFragment extends ConversationBaseFragment {
    private FragmentMyConversationBinding viewBinding;
    private List<ConversationBean> conversationBeans = new ArrayList<>();//全部会话
    private List<ConversationBean> searchConversation = new ArrayList<>();//搜索出来的

    @Override
    public View initViewAndGetRootView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        viewBinding = FragmentMyConversationBinding.inflate(inflater, container, false);
        initView();
        return viewBinding.getRoot();
    }

    private void initView() {
        conversationView = viewBinding.conversationView;

        networkErrorView = viewBinding.errorTv;
        emptyView = viewBinding.emptyLayout;

        setViewHolderFactory(new FunViewHolderFactory());
        viewBinding.conversationView.addItemDecoration(getItemDecoration());
        viewBinding.tvTitleBar.getRightLayout().setOnClickListener(v -> {


        });
        viewBinding.edtDiagnosis.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                searchConversation.clear();
                String keyWord = viewBinding.edtDiagnosis.getText().toString();
                for (int i = 0; i < conversationBeans.size(); i++) {
                    if (conversationBeans.get(i).infoData.getName().contains(keyWord)) {
                        searchConversation.add(conversationBeans.get(i));
                    }
                }
                conversationView.setData(searchConversation);
                setEmptyView();
            }
            return false;
        });

        viewBinding.edtDiagnosis.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

                String text = s.toString().trim();
                if (TextUtils.isEmpty(text)) {
                    updateView();
                }

            }
        });



        loadUIConfig();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        getViewModel().getQueryLiveData().observe(this.getViewLifecycleOwner(), result -> {
            conversationBeans=result.getData();
        });

        getViewModel().getChangeLiveData().observe(this.getViewLifecycleOwner(), result -> {

            if (result.getLoadStatus() == LoadStatus.Success) {
                    update(result.getData());
            } else if (result.getLoadStatus() == LoadStatus.Finish
                    && result.getType() == FetchResult.FetchType.Remove) {
                if (result.getData() == null || result.getData().size() < 1) {
                    conversationView.removeAll();
                } else {
                    conversationView.remove(result.getData());
                    removeData(result.getData());
                }
            }
        });
    }

    public void update(List<ConversationBean> data) {
        for (int i = 0; data != null && i < data.size(); i++) {
            update(data.get(i));
        }
    }

    public void update(ConversationBean data) {
        int removeIndex = -1;
        for (int j = 0; j < conversationBeans.size(); j++) {
            if (data.equals(conversationBeans.get(j))) {
                removeIndex = j;
                break;
            }
        }

        if (removeIndex > -1) {
            viewBinding.edtDiagnosis.setText("");
            conversationBeans.remove(removeIndex);
            int insertIndex = searchComparatorIndex(data);
            conversationBeans.add(insertIndex, data);
            updateView();
        } else {
            viewBinding.edtDiagnosis.setText("");
            int insertIndex = searchComparatorIndex(data);
            conversationBeans.add(insertIndex,data);
            updateView();
        }
    }

    public void removeData(List<ConversationBean> dataList) {
        if (dataList == null || dataList.size() < 1) {
            return;
        }
        for (ConversationBean data : dataList) {
            int index = -1;
            for (int j = 0; j < conversationBeans.size(); j++) {
                if (data.equals(conversationBeans.get(j))) {
                    index = j;
                    break;
                }
            }
            if (index > -1) {
                if (index >= 0 && index < conversationBeans.size()) {
                    conversationBeans.remove(index);
                }
            }
        }
    }
    public void updateView(){
        conversationView.setData(conversationBeans);
        setEmptyView();
    }


    private int searchComparatorIndex(ConversationBean data) {
        int index = conversationBeans.size();
        // add stick must be insert 0
        if (data.infoData.isStickTop()) {
            return 0;
        }
        for (int i = 0; i < conversationBeans.size(); i++) {
            if (conversationComparator != null
                    && conversationComparator.compare(data.infoData, conversationBeans.get(i).infoData) < 1) {
                index = i;
                break;
            }
        }

        return index;
    }

    public RecyclerView.ItemDecoration getItemDecoration() {
        return new RecyclerView.ItemDecoration() {
            final int topPadding = SizeUtils.dp2px(0.25f);
            final int indent = SizeUtils.dp2px(76);

            @Override
            public void onDrawOver(
                    @NonNull Canvas canvas, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                int left = parent.getPaddingLeft() + indent;
                int right = parent.getWidth() - parent.getPaddingRight();

                int childCount = parent.getChildCount();
                for (int i = 0; i < childCount - 1; i++) {
                    View child = parent.getChildAt(i);

                    RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();

                    int top = child.getBottom() + params.bottomMargin;
                    int bottom = top + topPadding;

                    Paint paint = new Paint();
                    paint.setColor(
                            parent.getResources().getColor(com.netease.yunxin.kit.conversationkit.ui.R.color.fun_conversation_item_divide_line_color));
                    canvas.drawRect(left, top, right, bottom, paint);
                }
            }
        };
    }

    private void loadUIConfig() {
        if (ConversationKitClient.getConversationUIConfig() == null) {
            return;
        }
        ConversationUIConfig config = ConversationKitClient.getConversationUIConfig();


        if (config.conversationComparator != null) {
            setComparator(config.conversationComparator);
        }

        if (config.conversationFactory != null) {
            setViewHolderFactory(config.conversationFactory);
        }

        if (config.customLayout != null) {
            config.customLayout.customizeConversationLayout(this);
        }
    }


    public LinearLayout getTopLayout() {
        return viewBinding.topLayout;
    }

    public LinearLayout getBodyLayout() {
        return viewBinding.bodyLayout;
    }

    public FrameLayout getBottomLayout() {
        return viewBinding.bottomLayout;
    }

    public FrameLayout getBodyTopLayout() {
        return viewBinding.bodyTopLayout;
    }

    public TextView getErrorTextView() {
        return viewBinding.errorTv;
    }

    public void setEmptyViewVisible(int visible) {
        viewBinding.emptyLayout.setVisibility(visible);
    }

    public View getEmptyView() {
        return viewBinding.emptyLayout;
    }
}
